package com.qmq.app.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmq.app.dao.UserDao;
import com.qmq.app.entity.UserEntity;
import com.qmq.app.entity.UserInfo;
import com.qmq.app.entity.UserPassword;
import com.qmq.app.form.LoginForm;
import com.qmq.app.form.RegisterForm;
import com.qmq.app.service.UserService;
import com.qmq.app.utils.StrUtils;
import com.qmq.common.exception.RRException;
import com.qmq.common.utils.Constant;
import com.qmq.common.utils.CreateCode;
import com.qmq.common.utils.PhotoUtils;
import com.qmq.common.validator.Assert;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Resource
    private PhotoUtils photoUtils;

    @Value("${default.header}")
    private String header;

    @Override
    public UserEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
    }

    @Override
    public UserEntity login(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("手机号或密码错误");
        }
        return user;
    }

    @Override
    public void reSetPassword(UserPassword password) {
        if (Objects.equals(password.getPassOld(), password.getPassNew())) {
            throw new RRException("新旧密码不能一致");
        }
        if (!Objects.equals(password.getPassNew(), password.getPassNewAffirm())) {
            throw new RRException("新密码不一致");
        }
        Optional<UserEntity> userEntity = Optional.ofNullable(baseMapper.selectOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getUserId, password.getUserId())));
        userEntity.orElseThrow(() -> new RRException("不存在的用户ID" + password.getUserId()));
        userEntity.ifPresent(user -> {
            if (!Objects.equals(user.getPassword(), DigestUtils.sha256Hex(password.getPassOld()))) {
                throw new RRException("密码错误!");
            }
            this.update(Wrappers.<UserEntity>lambdaUpdate()
                    .set(UserEntity::getPassword, DigestUtils.sha256Hex(password.getPassNew()))
                    .eq(UserEntity::getUserId, password.getUserId()));
        });
    }

    @Override
    public UserEntity reSetUserInfo(UserInfo info) {
        if (StrUtil.isAllBlank(info.getHeader(),info.getUserName())) {
            throw new RRException("用户信息未作出改变");
        }
        Optional<UserEntity> user = Optional.ofNullable(getOne(Wrappers.<UserEntity>lambdaQuery()
                .eq(UserEntity::getUserId, info.getUserId())));
        user.orElseThrow(()->new RRException("用户不存在"));
        LambdaUpdateWrapper<UserEntity> update = Wrappers.<UserEntity>lambdaUpdate().eq(UserEntity::getUserId, info.getUserId());
        user.ifPresent(u->{
            update.set(UserEntity::getUsername,info.getUserName());
            update.set(UserEntity::getHeader,info.getHeader());
            // 原头像不等于默认头像,并且传过来的数据不等于老头像时,要删除久文件
            if (!Objects.equals(header,u.getHeader())
                && !Objects.equals(u.getHeader(),info.getHeader())){
                photoUtils.delete(u.getHeader());
            }
            this.update(update);
        });
        return this.getUserInfo(info.getUserId());
    }

    @Override
    public UserEntity register(RegisterForm form) {
        if (!StrUtils.isEmail(form.getMobile())) {
            throw new RRException("邮箱格式错误");
        }
        if (!Objects.equals(form.getPassword(), form.getAffirmPassword())) {
            throw new RRException("前后密码不一致");
        }
        if (Objects.nonNull(queryByMobile(form.getMobile()))) {
            throw new RRException("该用户已存在");
        }
        UserEntity user = UserEntity.builder()
                .mobile(form.getMobile())
                .username(form.getMobile())
                .password(DigestUtils.sha256Hex(form.getPassword()))
                .createTime(new Date())
                .build();
        if (StrUtil.isNotEmpty(form.getCode())) {
            Optional.ofNullable(baseMapper.selectOne(Wrappers.<UserEntity>lambdaQuery()
                    .eq(UserEntity::getCode, form.getCode()).last(Constant.SEARCH_ONE))).ifPresent(parent -> {
                user.setParentId(parent.getUserId());
            });
        }
        user.setHeader(header);
        this.save(user);
        this.update(Wrappers.<UserEntity>lambdaUpdate()
                .set(UserEntity::getCode, CreateCode.toSerialCode(user.getUserId()))
                .eq(UserEntity::getUserId, user.getUserId())
        );
        return this.getUserInfo(user.getUserId());
    }

    @Override
    public UserEntity getUserInfo(Long userId) {
        UserEntity entity = UserEntity.builder().build();
        Optional.ofNullable(this.getOne(Wrappers.<UserEntity>lambdaQuery()
                .eq(UserEntity::getUserId, userId)
                .last(Constant.SEARCH_ONE))).ifPresent(user -> {
            BeanUtil.copyProperties(user, entity);
            entity.setParent(this.getOne(Wrappers.<UserEntity>lambdaQuery()
                    .eq(UserEntity::getUserId, entity.getParentId())
                    .last(Constant.SEARCH_ONE)
            ));
            entity.setInvitees(this.list(Wrappers.<UserEntity>lambdaQuery()
                    .eq(UserEntity::getParentId, entity.getUserId())
            ));
        });
        return entity;
    }
}
